package com.HelloWidget;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Random;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.RemoteViews;

public class ContentUpdateService extends WakefulIntentService {

	private ArrayList <ContentDescriptor> _providers;
	private Random _rnd;
	public static String WIDGET_CONTENT_ACTION = "WidgetPresedToGetContent";
	public static String WIDGET_SETTINGS_ACTION = "WidgetPresedToGetSettings";
	public static String WIDGET_NEXT_EUREKA_ACTION = "WidgetPresedToGetNextItem";

	public ContentUpdateService () {
		super("ContentUpdateService");
		Log.d("ContentUpdateService","ctor2");

	}
	public ContentUpdateService(String name) {
//		Log.d("ContentUpdateService","ctor1");
		super(name);
		Log.d("ContentUpdateService","ctor2");
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void doWakefulWork(Intent intent) {
		ComponentName cn = new ComponentName(this, HelloWidget.class);
		AppWidgetManager awm = AppWidgetManager.getInstance(this);
		RemoteViews updatedWidget = buildUpdate(intent);
		awm.updateAppWidget(cn, updatedWidget);
	}


	private RemoteViews buildUpdate(Intent intentOrig) {
		//TODO: use configuration settings
		Context context = this.getApplicationContext();
		RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.main);
//		updatedWidget.setTextViewText(R.id.widget_textview_headline, "service test");
		_rnd = new Random();
		try {
			refreshProviders();
			ContentDescriptor des = getDescriptorFromProviders();
			remoteViews.setTextViewText(R.id.widget_textview_headline,
					des.getHeadline());
			//						"test");
			remoteViews.setTextViewText(R.id.widget_textview_description,
					des.getDescription());
			String imgUrl = des.getBitmapUrl(); //todaysArticle[3]; //getWikipediaImageUrl();
			Bitmap bitmap = getImageBitmap(imgUrl);
			//System.out.println(wikiBitmap);
			remoteViews.setImageViewBitmap(R.id.widget_imageview, bitmap);

			//				Uri imgUri = Uri.parse(imgUrl); 
			//	            Uri artUri = Uri.parse(todaysArticle[2]); 
			//				Intent intentImg = new Intent(Intent.ACTION_VIEW, artUri);  
			//				PendingIntent pendingIntentImg = PendingIntent.getActivity(_context, 0, intentImg, 0);
			//
			//	            // Get the layout for the App Widget and attach an on-click listener to the button
			//	            remoteViews.setOnClickPendingIntent(R.id.widget_imageview, pendingIntentImg);
			//					            
			//				Intent intent = new Intent(Intent.ACTION_VIEW, artUri);  
			//				PendingIntent pendingIntent = PendingIntent.getActivity(_context, 0, intent, 0);
			//
			//	            // Get the layout for the App Widget and attach an on-click listener to the button
			//	            remoteViews.setOnClickPendingIntent(R.id.widget_textview_description, pendingIntent);
			//	            remoteViews.setOnClickPendingIntent(R.id.widget_textview_headline, pendingIntent);
			//				
			// Create an Intent to launch ExampleActivity
			Intent intent = new Intent(context, WebActivity.class);
			intent.putExtra("com.HelloWidget.WebActivity.artUrl", des.getUrl());
			PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);	            
			intent.setAction(WIDGET_CONTENT_ACTION);
			remoteViews.setOnClickPendingIntent(R.id.widget_textview_description, pendingIntent);
			remoteViews.setOnClickPendingIntent(R.id.widget_textview_headline, pendingIntent);
			remoteViews.setOnClickPendingIntent(R.id.widget_imageview, pendingIntent);
			//System.out.println(_context);
			//System.out.println(appWidgetManager);
			//System.out.println(HelloWidget.class);

			intent = new Intent(context, ConfigurationActivity.class);
			//FIXME: change 0 to widget id to allow more than one instance of the widget
			intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, 0); 
			pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);	            
			intent.setAction("android.appwidget.action.APPWIDGET_CONFIGURE");
			remoteViews.setOnClickPendingIntent(R.id.imageButton1, pendingIntent);
			
			Intent nextIntent = new Intent();
			nextIntent.setAction(WIDGET_NEXT_EUREKA_ACTION);
			PendingIntent nextPendingIntent = PendingIntent.getActivity(context, 0, nextIntent, PendingIntent.FLAG_CANCEL_CURRENT);	            
			remoteViews.setOnClickPendingIntent(R.id.imageButton2, nextPendingIntent);

		}

		catch (Exception e) {
			e.printStackTrace();
		}


		return remoteViews;
	}
	
	private void refreshProviders() {
		if (null == _providers) {
			_providers = new ArrayList<ContentDescriptor>();

			_providers.add(new WikipediaTodaysFeaturedArticle());
			_providers.add(new WikipediaTodaysFeaturedPicture());
			_providers.add(new NationalGeographicPhotoOfTheDay());
			_providers.add(new YoutubeDailyTop());
			_providers.add(new VimeoVideoOfTheDay());
		}
	}
	
	private ContentDescriptor getDescriptorFromProviders() {			
		if (_providers.size() == 0)
			return null;
		int providerIndex = _rnd.nextInt(_providers.size());
		boolean found = false;
		//SharedPreferences sp=PreferenceManager.getDefaultSharedPreferences(_context);
		ContentDescriptor des = _providers.get(providerIndex);

		while (!found) {
			des = _providers.get(providerIndex);
			String type =des.getType();
			if (!checkType(type))
				continue;
			if (!des.isInitialized())
				try {
					des.init();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					continue;
				}
				found = true;
		}

		return des;
		////FIXME: change 0 to widget id to allow more than one instance of the widget
		//boolean setting = sp.getBoolean(type+"0", false); 
		//System.out.println("type:"+type+" setting:"+setting);
		//providerIndex = _rnd.nextInt(_providers.size());
		//des = _providers.get(providerIndex);
		//type =des.getType();

	}

	private boolean checkType(String type) {
		// TODO Auto-generated method stub
		return true;
	}

	private Bitmap getImageBitmap(String url) { 
		Bitmap bm = null; 
		try { 
			URL aURL = new URL(url); 
			URLConnection conn = aURL.openConnection(); 
			conn.connect(); 
			InputStream is = conn.getInputStream(); 
			BufferedInputStream bis = new BufferedInputStream(is); 
			bm = BitmapFactory.decodeStream(bis); 
			bis.close(); 
			is.close(); 
		} catch (IOException e) { 
			Log.e("TAG", "Error getting bitmap", e); 
		} 
		return bm; 
	} 

}
